package com.xsh.daw;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yanzhenjie.permission.runtime.PermissionRequest;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

public class MainActivity extends AppCompatActivity implements CopyCallback {
    public TextView debug;
    private File externalStorageDir;
    private String nativeLibraryDir;
    private File appFilesDir;

    static {
        System.loadLibrary("dawtest");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,REQUEST_CODE});
        debug = findViewById(R.id.mydebug);
        externalStorageDir = Environment.getExternalStorageDirectory();
        nativeLibraryDir = getApplicationInfo().nativeLibraryDir;
        appFilesDir = getFilesDir();
        if(AndPermission.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE))
        {
            Log.d(MainActivity.class.toString(),"有读取外部权限");
            testLibCopy();
            // 雷电模拟器测试
            //testLibCopy();
            //testWrite();
        }
        else
            {
                PermissionRequest pr = AndPermission.with(this).runtime().permission(Permission.Group.STORAGE);
                pr.start();
                // 安卓13权限 >android 11 >android 11
               /* if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.R)
                {
                    if(!Environment.isExternalStorageManager())
                    {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                        startActivity(intent);
                    }
                }*/

                pr.onGranted(new Action<List<String>>() {
                @Override
                public void onAction(List<String> permissions)
                {
                    Toast.makeText(MainActivity.this,"权限申请成功",Toast.LENGTH_SHORT).show();
                    testLibCopy();
                }
            });
                pr.onDenied(new Action<List<String>>()
                {
                    @Override
                    public void onAction(List<String> data)
                    {
                        Toast.makeText(MainActivity.this,"你拒绝了文件读取权限，将无法导入插件",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        // >= android M 5.2
      //  if(EasyPermissions.hasPermissions(getApplicationContext(),Permiss))
    }
    public void pluginManage(View v)
    {
        Intent i = new Intent(MainActivity.this,PluginManage.class);
        startActivity(i);
    }
    public void testWrite()
    {
        File dir = getFilesDir();
        File f = new File(dir,"test.txt");
        try{
            FileWriter fw = new FileWriter(f);
            fw.write("test");
            fw.close();
        }catch (Exception e){e.printStackTrace();}

        Toast.makeText(this,"文件： "+f.exists(),Toast.LENGTH_SHORT).show();
        debug.setText("文件： "+f.exists());
    }
    public void testLibCopy()
    {
        Log.d(MainActivity.class.toString(),"testLibCopy");
        File srcFile = new File(externalStorageDir,"mydir/x86/libstringfromso.so");
        if (!srcFile.exists()) {
            Log.e("MainActivity", "源文件不存在: " + srcFile.getAbsolutePath());
            debug.setText("文件不存在");
        }
        else
            {

                Log.d(MainActivity.class.toString(),"文件存在:" + srcFile.getAbsolutePath());
                debug.setText("文件存在");
                boolean copycode = FileUtils.copyFile(srcFile.getAbsolutePath(),appFilesDir.getAbsolutePath(),this);
                if(copycode == true)
                {
                    Log.d(MainActivity.class.toString(), "请检查: " + appFilesDir);

                    // test(appFilesDir.getAbsolutePath()+"/libstringfromso.so");
                    //  String a = getStringVar(appFilesDir + "/libstringfromso.so");
                    //  String b = getStringFromFunc(appFilesDir + "/libstringfromso.so");
                    // String c = hello();
//                     Log.d(MainActivity.class.toString(),a);
//                    Log.d(MainActivity.class.toString(),a);
//                        Log.d(MainActivity.class.toString(),b);
                    String copyedSo = appFilesDir + "/libstringfromso.so";
                    init(copyedSo);
                    getVarAfterInit(copyedSo);
                    getVar2AfterInit(copyedSo);
                }
                else{
                    Log.e(MainActivity.class.toString(),"复制失败");
                }

            }
    }
    //test
    public native String getStringVar(String libpath);
    public native String getStringFromFunc(String libpath);
    public native String hello();
    public native void test(String libpath);
    public native void init(String libpath);
    public native void getVarAfterInit(String libpath);
    public native void getVar2AfterInit(String libpath);
    @Override
    public void onComplete(boolean success, String messages)
    {
        if(success)
        {
            Log.d("lib copy finish",messages);
        }
        else
        {Log.d(MainActivity.class.toString(),messages);}
    }
   /* @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
       //EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }*/
}